<!-- 组织架构图左侧组件 -->

<template>
  <div class="left-list">
    <div @click="collapse" class="collapseBtn">
      <IconCaretRight v-if="isCollapsed" />
      <IconCaretLeft v-else />
    </div>
    <a-layout class="layout-demo">
      <a-layout-sider
        collapsible
        breakpoint="xl"
        hide-trigger
        :collapsed="isCollapsed"
        :collapsed-width="0"
      >
        <div class="role-list" v-show="!isCollapsed">
          <div>
            <a-scrollbar style="height: 600px; overflow: auto">
              <div class="scroll">
                <a-input-search
                  allow-clear
                  class="search"
                  placeholder="输入分类名称"
                  v-model="searchVal"
                />

                <div class="scroll-content">
                  <a-tree
                    v-model:selected-keys="selectedKeys"
                    @select="select"
                    :fieldNames="{
                      key: 'id',
                      title: 'department',
                      children: 'children'
                    }"
                    showLine
                    :data="treeData"
                    v-model:expanded-keys="expandKey"
                  >
                    <template #switcher-icon="node, { isLeaf }">
                      <IconDown v-if="!isLeaf" />
                      <IconStar v-if="isLeaf" />
                    </template>
                    <template #title="nodeData">
                      <template
                        v-if="
                          ((index = getMatchIndex(nodeData.name)), index < 0)
                        "
                      >
                        <span
                          :style="{
                            paddingLeft:
                              nodeData.level > 2
                                ? '32px'
                                : (nodeData.level - 1) * 16 + 'px'
                          }"
                        >
                          {{ nodeData?.name }}
                        </span>
                      </template>
                      <span v-else>
                        {{ nodeData?.name?.substr(0, index) }}
                        <span style="color: var(--color-primary-light-4)">
                          {{
                            nodeData?.name?.substr(index, searchVal.length)
                          }} </span
                        >{{ nodeData?.name?.substr(index + searchVal.length) }}
                      </span>
                    </template>
                  </a-tree>
                </div>
              </div>
            </a-scrollbar>
          </div>
        </div>
      </a-layout-sider>
    </a-layout>
  </div>
</template>

<script lang="ts" setup>
import clonedeep from 'lodash.clonedeep';
import { flatTreeWithChildren } from '@/utils/utils';
import { GetContractGroup } from '@/apis/management/contract/baseSetting';
import type { treeDataType } from '../../type';

const emit = defineEmits(['clickTree']);
const props = withDefaults(
  defineProps<{
    data?: treeDataType; // 是否显示对话框
    id?: number; // 组织id
  }>(),
  {
    data: () => ({})
  }
);
let searchVal = ref(''); // 搜索框
let selectedKeys = ref([]); // 选中的key
let ContractGroupTreeData = ref<treeDataType[]>([]); // 储存最初的树形数据
let expandKey: any = ref([]); // 储存当前搜索要展开的选项
const GetContractType = async () => {
  try {
    const data = await GetContractGroup({ pageNumber: 0, pageSize: -1 });
    ContractGroupTreeData.value = data.content;
  } catch (err: unknown) {
    console.log(err);
  }
};
GetContractType();

// 搜索值
const searchData = (keyword: string) => {
  const loop = (data: any) => {
    const result: any = [];
    data.forEach((item: any) => {
      if (item.department.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
          expandKey.value.push(item.id);
        }
      }
    });
    return result;
  };
  return loop(originTreeData.value);
};
let isCollapsed = ref(false); // 判断是否收起
const collapse = (collapsed: boolean) => {
  isCollapsed.value = !isCollapsed.value;
};
/* 储存实时的属性数据 */
const treeData = computed(() => {
  if (!searchVal.value) return ContractGroupTreeData.value;
  return searchData(searchVal.value);
});
// watch(
//   () => props.data,
//   (val) => {
//     originTreeData.value = [val];
//     selectedKeys.value = [originTreeData.value[0].id]; // 默认选中第一条数据
//     // 如果是从组织机构列表跳转过来则直接显示对应id的数据
//     if (props.id > 0) {
//       const temp = flatTreeWithChildren([val]).find(
//         (item: any) => item.id === props.id
//       );
//       // 直接用跳转过来组织的名字来搜索展开子树，然后将id赋值给selectedKeys
//       searchData(temp.department);
//       selectedKeys.value = [props.id];
//       emit('clickTree', temp);
//     }
//   }
// );
// 获取符合的数据
const getMatchIndex = (name: string): number => {
  if (!searchVal.value) return -1;
  return name.toLowerCase().indexOf(searchVal.value.toLowerCase()) as number;
};

// 点击树触发
const select = (e: any, { selectedNodes }: any) => {
  emit('clickTree', selectedNodes[0]);
};
</script>

<style scoped lang="less">
.left-list {
  position: relative;
  padding: 0 15px;

  .collapseBtn {
    position: absolute;
    z-index: 9;
    top: 40%;
    right: 15px;
    height: 70px;
    width: 15px;
    background-color: #eee;
    line-height: 70px;
    text-align: center;
    cursor: pointer;
  }
  .layout-demo {
    height: 100%;
  }
  .layout-sider {
    // width: 350px;
  }
  .arco-layout {
    flex: none !important;
  }
  .role-list {
    flex: 1;
    .scroll {
      padding: 10px;
      .search {
        background-color: #fff;
        height: 40px;
        border: 1px solid #ccc;
      }
    }
  }
}
:deep(.arco-layout-sider-trigger) {
  position: absolute;
  bottom: 0px;
  right: 20px;
  width: 20px !important;
  background: transparent;
}
:deep(.arco-tree-node-indent) {
  width: 0px;
  height: 0px;
}
</style>
